<template>
  <div class="container margin-top-10">
    <div class="row">
      <!-- 左侧 -->
      <div class="col-8">
        <h4>{{userInfo.username}}的空间</h4>
        <blog-item
          :blog="blog"
          :key="blog.id"
          v-for="blog in blogs"
        />
        <div class="loading-more">{{loadingText}}</div>
      </div>
      <!-- 右侧 -->
      <div class="col-4">
        <div class="right-item">
          <div class="user-info">
            <img
              :src="userInfo.avatar"
              class="avatar"
            />
            <span class="user-name">{{userInfo.username}}</span>
          </div>

          <p
            class="margin-top-10"
            v-if="userId != $store.state.userInfo.id"
          >
            <button
              @click="unFollow"
              class="btn btn-light"
              v-if="userInfo.isFollow"
            >取消关注</button>
            <button
              @click="onFollow"
              class="btn btn-primary"
              v-else
            >关注</button>
          </p>
        </div>
        <hr class="hr-line" />
        <div class="user-list right-item">
          <p class="title bold">
            ✨
            关注（{{userInfo.follower}}）
            <i
              @click="getUserFollow"
              class="iconfont icon-below-s"
              title="展开"
            ></i>
          </p>
          <div
            class="follow"
            v-if="follows"
          >
            <a
              :key="follow.id"
              @click.prevent="$router.push(`/space/${follow.id}`)"
              href="#"
              v-for="follow in follows"
            >
              <img
                :src="follow.avatar"
                class="follow-avatar"
              />
              <span>{{follow.username}}</span>
            </a>
          </div>
        </div>

        <div class="user-list right-item">
          <p class="title bold">
            💋
            粉丝（{{userInfo.fans}}）
            <i
              @click="getUserFans"
              class="iconfont icon-below-s"
              title="展开"
            ></i>
          </p>
          <div
            class="fans"
            v-if="fans"
          >
            <a
              :key="fan.id"
              @click.prevent="$router.push(`/space/${fan.id}`)"
              href="#"
              v-for="fan in fans"
            >
              <img
                :src="fan.avatar"
                class="follow-avatar"
              />
              <span>{{fan.username}}</span>
            </a>
          </div>
        </div>
      </div>

      <!-- 右侧结束 -->
    </div>
  </div>
</template>

<script>
import {
  getCurrentInstance, ref,
  reactive, watch
} from "vue";
import {
  onBeforeRouteUpdate,
} from 'vue-router'

import BlogItem from "../../components/blog-item/BlogItem";
import debounce from '../../utils/debounce'
import {
  followUser,
  getUserInfo,
  unFollowUser,
  getUserFollowDetail,
  getUserFansDetail,
} from "../../network/user";
import { getBlogs } from "../../network/blog";

export default {
  name: "Space",
  components: { BlogItem },
  setup(props, content) {
    const { ctx } = getCurrentInstance();
    const userId = ref(ctx.$router.currentRoute.value.params.userId);
    const userInfo = ref({}); //用户信息
    const blogs = ref(null); //微博信息
    const currentPage = ref(1); //当前页码
    const loadingText = ref("加载更多……");
    const follows = ref(null);
    const fans = ref(null);
    const windowHeight = ref(
      document.documentElement.clientHeight || document.body.clientHeight
    ); //视口高度


    onBeforeRouteUpdate((to, from, next) => {
      userId.value = to.params.userId
      userInfo.value = {}
      blogs.value = null
      currentPage.value = 1
      loadingText.value = "加载更多……"
      fans.value = follows.value = null
      getUserBlogs(currentPage.value)
      loadUserInfo(userId.value)
      next()
    })

    //滚动到底部加载更多事件
    const listenToScroll = () => {
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      //变量scrollHeight是滚动条的总高度
      var scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;

      if (scrollTop + windowHeight.value > scrollHeight - 100) {
        loadingText.value === "加载更多……" && getUserBlogs(currentPage.value);
      }
    };

    //监听滚动事件
    window.addEventListener("scroll", debounce(listenToScroll, 200));


    //获取用户博客
    const getUserBlogs = async (page) => {
      const data = {
        userId:userId.value,
        page,
        limit: 10,
      };
      const result = await getBlogs(data);
      if (result.status !== 200) {
        return console.log(result.message);
      }
      currentPage.value = result.data.page + 1;
      blogs.value =
        page === 1
          ? result.data.result
          : [...blogs.value, ...result.data.result];
      loadingText.value =
        result.data.result.length < 10 ? "已加载全部~" : "加载更多……";
    };
    getUserBlogs(currentPage.value);

    //关注用户
    const onFollow = async () => {
      const result = await followUser(userId.value);
      if (result.status !== 200) {
        return console.log(result.message);
      }
      userInfo.value.isFollow = true;
      userInfo.value.fans++;
      userInfo.value = { ...userInfo.value };
    };
    // 取消关注
    const unFollow = async () => {
      const result = await unFollowUser(userId.value);
      if (result.status !== 200) {
        return console.log(result.message);
      }
      userInfo.value.isFollow = false;
      userInfo.value.fans--;
      userInfo.value = { ...userInfo.value };
    };
    //获取用户信息
    const loadUserInfo = async (userId) => {
      const result = await getUserInfo(userId);
      // console.log(result);
      if (result.status !== 200) {
        return console.log("获取用户信息失败");
      }
      userInfo.value = result.data;
    };
    loadUserInfo(userId.value);

    //获取用户关注用户详情
    const getUserFollow = async () => {
      if(follows.value) return
      const result = await getUserFollowDetail(userId.value);
      // console.log(result);
      if (result.status !== 200) {
        return console.log("获取失败");
      }
      follows.value = result.data.result;
    };
    //获取用户粉丝详情
    const getUserFans = async () => {
      if(fans.value) return
      const result = await getUserFansDetail(userId.value);
      // console.log(result);
      if (result.status !== 200) {
        return console.log("获取失败");
      }
      fans.value = result.data.result;
    };

    return {
      onFollow,
      unFollow,
      follows,
      fans,
      blogs,
      userId,
      userInfo,
      loadingText,
      getUserFollow,
      getUserFans,
    };
  },
};
</script>

<style scoped lang='stylus' >
.margin-top-10
  margin-top 10px

  .user-info
    margin-bottom 17px

  .user-name
    font-size 24px
    font-weight bold
    margin-left 10px

.avatar
  width 60px
  height 60px
  border-radius 50%

.bold
  font-weight bold
  color #666

.hr-line
  margin 30px 0

.loading-more
  margin 10px 0
  text-align center

.fans-avatar, .follow-avatar
  width 36px
  height 36px
  border-radius 50%
  margin-left 5px
  margin-bottom 7px
</style>